<?php
/**
 * 基于phpqrcode库二维码生成
 * @文件名称: Qrcode.php
 * @author: jawei
 * @Email: gaozhiwei@etcp.cn
 * @Date: 2017-06-06
 * @Copyright: 2017 悦畅科技有限公司. All rights reserved.
 * 注意：本内容仅限于悦畅科技有限公司内部传阅，禁止外泄以及用于其他的商业目的
 */
namespace app\lib;

use app\base\BaseService;
use Yii;
use app\lib\Upload;
class Qrcode 
{
    /**
     * 生成二维码
     * @params  array   msg 中包含的是图片的地址
     **/
    public static function create($data, $filename,$level = 'M', $pointSize = 5, $prefix = 'png')
    {
        include Yii::$app->basePath . "/lib/phpqrcode/qrlib.php";
        $uid = User::getUserId();
        $filename =  $filename . '.' . $prefix;
        $dir = Yii::$app->basePath . '/runtime/qrcode/' . $uid;
        if (!is_dir($dir)) {
            mkdir($dir);
        }
        $file = $dir . '/' . $filename;
        $rs = \QRcode::png($data,$file, $level, $pointSize, 2); 
        if (file_exists($file)) {
            $rs = Upload::toYun($file, false, false, '/qrcode/' . $uid . '/') ;
            if ($rs['errno'] != 200) {
                return ['errno' => $rs['errno'], 'msg' => '上传至又拍云失败'] ;
            }
			return [
				'errno' => 200, 
				'msg' => 'http://' . Yii::$app->params['yun']['app'] . $rs['file']
			];
        }
        return ['errno' => 500, 'msg' => '生成文件失败'];
    }

    /**
     * 创建一个 hash中的值
     *
     * @return string
     * @author  doujm
     **/
    public static function createValue($code, $phone)
    {
        //$value = $imgCode . '_' . $phone_num;
        return $code . '_' . $phone;
    }

    /**
     *  生成图片验证码
     *
     * @return array
     **/
    public static function createImgcode($phone_num)
    {
        try {
            $code = Common::getRandChar(4);
            $session = Yii::$app->session;
            $session->set('imgCode' , $code);
            $data = [
                'data' => [
                    'post'  => $code,
                    'img'  => Yii::$app->params['host'] . 'img/code?code=' . $code,
                ],
            ];
            BaseService::returnOkData($data);
        } catch (\ErrorException $e) {
            $log = [
                'msg' => $e->getMessage(),
                'phone' => $phone_num,
                'line' => $e->getLine(),
            ] ;
            Trace::addLog('qrcode_creatImg_exception', 'warning', $log);
            return ['errno' => 500, 'msg' => '生成图片验证码失败'];
        }
    }
}
